package memento_pattern;

import java.util.Stack;

/**
 * @author 申书航
 * @version 1.0
 * 游戏核心类，负责棋局的管理和玩家的落子操作。
 */
public class GameCore {

    private final Chessboard board;

    private final Stack<ChessboardMemento> mementos;

    private boolean isBlack;

    /**
     * 构造函数，初始化棋盘和备忘录栈。
     */
    public GameCore() {
        board = new Chessboard();
        mementos = new Stack<>();
    }

    /**
     * 玩家落子操作，记录当前状态并添加棋子。
     * @param x 棋子的横坐标
     * @param y 棋子的纵坐标
     */
    public void playChess(int x, int y) {
        //记录上一步
        mementos.push(board.save());
        //执行落子
        Chessman chessman = new Chessman(x, y);
        if (isBlack) {
            chessman.setColor('●');
            System.out.println("黑棋落子：" + x + "," + y);
        }
        else {
            chessman.setColor('○');
            System.out.println("白棋落子：" + x + "," + y);
        }
        board.addChessman(chessman);
        //修改下次落子方
        isBlack = !isBlack;
    }

    /**
     * 撤销上一步操作，将棋盘恢复到之前的状态。
     */
    public void undo() {
        if (mementos.isEmpty()) {
            System.out.println("没有可撤销的操作！");
            return;
        }
        //修改下次落子方为悔棋方
        isBlack = !isBlack;
        //悔棋
        System.out.println((isBlack? "黑棋" : "白棋") + "悔棋");
        ChessboardMemento pop = mementos.pop();
        board.restore(pop);
    }

    /**
     * 程序入口，创建游戏实例并进行一系列棋局操作。
     * @param args 命令行参数
     */
    public static void main(String[] args) {
        GameCore gameCore = new GameCore();
        gameCore.playChess(1, 1);
        gameCore.playChess(1, 2);
        gameCore.undo();
        gameCore.undo();
        gameCore.playChess(2, 1);
        gameCore.playChess(3, 1);
    }
}
